Public Class frmQueryAssist
    Inherits System.Windows.Forms.Form

    ''' <summary>
    ''' StationID, PCode, CCode, and RCode allow selection based on Support table; others allow selection using wildcards, ranges, etc.
    ''' </summary>
    Friend Enum enumAssist
        StationID
        PCode
        CCode
        RCode
        QCode
        Agency
        Validate
        DateTimeValue
        RealValue
        StringValue
    End Enum

    Private AssistType As enumAssist
    Private FieldName As String
    Private TableName As String

    Private FilterString As String = ""
    Private LastTxt As TextBox

    Friend Sub New(ByVal _TableName As String, ByVal _FieldName As String, ByVal _AssistType As enumAssist)
        InitializeComponent()
        TableName = _TableName
        FieldName = _FieldName
        AssistType = _AssistType
    End Sub

    Private Sub frmQueryAssist_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        If Project.DataSet.Tables.Contains("Validation") Then Project.DataSet.Tables.Remove("Validation") 'may need to reload for different field name next time
        SaveWindowPos(REGAPP, Me)
    End Sub

    Private Sub frmQueryAssist_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            GetWindowPos(REGAPP, Me)
            Select Case AssistType
                Case enumAssist.StationID To enumAssist.Validate
                    Me.pnlValues.Visible = False
                    Me.pnlSupport.Visible = True
                    Me.btnSelectFromGroups.Enabled = AssistType <= enumAssist.PCode
                    Dim SupportTable As String = Choose(AssistType + 1, "Stations", "PCodes", "CCodes", "RCodes", "QCodes", "Agencies", "Validation")
                    Dim SupportField As String = Choose(AssistType + 1, "Station_ID", "PCode", "CCode", "RCode", "QCode", "Agency", "Validation")
                    If Not Project.ResetPDox(SupportTable) Then Exit Sub
                    With Project
                        If .DataSet Is Nothing Then .DataSet = New DataSet
                        If .DataSet.Tables.IndexOf(SupportTable) = -1 Then 'not already loaded, do so now
                            If AssistType = enumAssist.Validate Then
                                .DB.AddTable(.DataSet, SupportTable, "Select Valid_Value,Description from Validation WHERE {0}(Field_Name) = '{1}'", Project.DB.UCase, FieldName.ToUpper)
                            Else
                                .DB.AddTable(.DataSet, SupportTable, "Select * from {0} ORDER BY {1}", SupportTable, SupportField)
                            End If
                            Try
                                .SetTableHeadings(.GetTableType(SupportTable))
                            Catch ex As Exception
                                WarningMsg(ex.Message)
                            End Try
                        End If
                        Me.dgSupport.DataSource = .DataSet.Tables(SupportTable)
                        lblAvailableValues.Text = lblAvailableValues.Text.Replace(":", " (" & dgSupport.RowCount & " records):")
                    End With
                    Project.ResetPDox()
                    With Me.dgSupport
                        For Each col As DataGridViewColumn In .Columns
                            col.HeaderText = col.HeaderText.Replace("_", " ")
                        Next
                        .ReadOnly = True
                        .AllowUserToResizeRows = False
                        .AllowUserToResizeColumns = True
                        .AutoResizeRows(IIf(.RowCount <= 1000, DataGridViewAutoSizeRowsMode.AllCells, DataGridViewAutoSizeRowsMode.DisplayedCells))
                        .AutoResizeColumns(IIf(.RowCount <= 1000, DataGridViewAutoSizeColumnsMode.AllCells, DataGridViewAutoSizeColumnsMode.DisplayedCells))
                        .RowHeadersVisible = False
                        .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                        .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                        .Sort(.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
                    End With
                    Dim bs As New BindingSource(dgSupport.DataSource, dgSupport.DataMember)
                    bs.RemoveFilter()
                    AcceptButton = btnAdd
                    CancelButton = btnCancel
                Case Else 'date assist
                    Me.pnlValues.Visible = True
                    Me.pnlSupport.Visible = False
                    Me.pnlValues.BringToFront()
                    Me.btnOK.BringToFront()
                    Me.btnCancel.BringToFront()
                    If Me.AssistType = enumAssist.DateTimeValue Then
                        Me.optDateTime.Checked = True
                        Me.grpDates.Visible = True
                    Else
                        Me.optEqual.Checked = True
                        Me.grpValues.Visible = True
                    End If
                    AcceptButton = btnOK2
                    CancelButton = btnCancel2
            End Select
            If AssistType = enumAssist.StationID Then btnGIS.Visible = True
            FilterTables()
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            MainForm.ProgressComplete()
        End Try
    End Sub

    Private Sub btnSelectAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectAll.Click
        For Each row As DataGridViewRow In Me.dgSupport.Rows
            row.Selected = True
        Next
        UpdateSelected()
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Me.SuspendLayout()
        For Each row As DataGridViewRow In Me.dgSupport.Rows
            If row.Selected AndAlso Not lstSelected.Items.Contains(row.Cells(0).Value) Then Me.lstSelected.Items.Add(row.Cells(0).Value)
        Next
        UpdateSelected()
        Me.ResumeLayout(True)
    End Sub

    Private Sub dgSupport_CellContentDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgSupport.CellContentDoubleClick
        Me.lstSelected.Items.Add(Me.dgSupport.Item(0, e.RowIndex).Value)
        UpdateSelected()
    End Sub

    Private Sub btnClearSelected_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearSelected.Click
        Me.lstSelected.Items.Clear()
        UpdateSelected()
    End Sub

    Private Sub txt1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt1.LostFocus, txt2.LostFocus
        LastTxt = CType(sender, TextBox)
    End Sub

    Private Sub lstSelected_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lstSelected.MouseDoubleClick
        With Me.lstSelected
            If .SelectedItems.Count > 0 Then .Items.Remove(.SelectedItem())
            UpdateSelected()
        End With
    End Sub

    ''' <summary>
    ''' Refresh the list so that only the stations that exist in the currently selected browser appear
    ''' </summary>
    Private Sub chkAvail_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkAvail.CheckedChanged
        FilterTables()
    End Sub

    Private Sub FilterTables()
        Dim SupportTable As String = Choose(AssistType + 1, "Stations", "PCodes", "CCodes", "RCodes", "QCodes", "Agencies", "Validation")
        If Not Project.DataSet.Tables.Contains(SupportTable) Then Exit Sub
        Dim bs As New BindingSource(Project.DataSet, SupportTable)
        Try
            With Project
                If Not Project.ResetPDox(SupportTable) Then Exit Sub
                If Me.chkAvail.Checked Then
                    MainForm.WriteProgress("Selecting unique values...", ProgressBarStyle.Marquee)
                    Dim FilterList As String = ""
                    For Each s As String In .DB.GetRecordList(TableName, FieldName)
                        FilterList &= String.Format("{0}'{1}'", IIf(FilterList = "", "", ", "), s.Replace("'", ""))
                    Next
                    If AssistType = enumAssist.Validate Then
                        If FilterList <> "" Then bs.Filter = String.Format("Valid_Value IN ({0})", FilterList)
                    Else
                        If FilterList <> "" Then bs.Filter = String.Format("{0} IN ({1})", FieldName, FilterList)
                    End If
                    MainForm.ProgressComplete()
                Else
                    bs.RemoveFilter()
                End If
                If Not Project.ResetPDox() Then Exit Sub
                Me.dgSupport.DataSource = bs
            End With
        Catch ex As Exception
            If bs IsNot Nothing Then bs.RemoveFilter()
            ErrorMsg("There are too many stations to filter.", ex)
        End Try
    End Sub

    Private Sub btnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind.Click
        Try
            With New frmFind
                .DataGrid = Me.dgSupport
                .Show(Me)
            End With
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub btnFilter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFilter.Click
        Try
            With New frmFilter
                .DataGrid = Me.dgSupport
                .txtFilterString.Text = FilterString
                .ShowDialog(Me)
                FilterString = .txtFilterString.Text
                .Dispose()
            End With
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub lstSelected_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstSelected.SelectedValueChanged
        UpdateSelected()
    End Sub

    Private Sub opt_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optEqual.CheckedChanged, optLess.CheckedChanged, optGreater.CheckedChanged, optRange.CheckedChanged, optNotRange.CheckedChanged, optWildcard.CheckedChanged, optList.CheckedChanged
        If Me.optRange.Checked Or Me.optNotRange.Checked Then
            Me.lbl1.Text = "Enter minimum value (inclusive):"
            Me.lbl2.Text = "Enter maximum value (inclusive):"
        ElseIf Me.optWildcard.Checked Then
            Me.lbl1.Text = "Enter string (wildcards are * and ?):"
        ElseIf Me.optList.Checked Then
            Me.lbl1.Text = "Enter comma-separated list:"
        Else
            Me.lbl1.Text = "Enter value:"
        End If

        If Me.optRange.Checked Or Me.optNotRange.Checked Then
            Me.lbl2.Visible = True
            Me.txt2.Visible = True
        Else
            Me.lbl2.Visible = False
            Me.txt2.Visible = False
        End If
        Me.txt1.Text = ""
        Me.txt2.Text = ""
    End Sub

    Private Sub optDT_CheckedChanged1(ByVal sender As Object, ByVal e As System.EventArgs) Handles optDateTime.CheckedChanged, optDate.CheckedChanged, optTime.CheckedChanged, optMonthYear.CheckedChanged, optMonth.CheckedChanged, optYear.CheckedChanged, optDTRange.CheckedChanged
        Me.btnDisplayList.Enabled = True
        If Me.optDateTime.Checked Then
            Me.lbl1.Text = "Enter date and time as " & MyDateTimeFormat().ToLower & ":"
        ElseIf Me.optDate.Checked Then
            Me.lbl1.Text = "Enter date as " & MyDateFormat().ToLower & ":"
        ElseIf Me.optTime.Checked Then
            Me.lbl1.Text = "Enter hour as hh:"
            Me.lbl2.Text = "Enter minute as mm:"
            Me.btnDisplayList.Enabled = False
        ElseIf Me.optMonthYear.Checked Then
            Me.lbl1.Text = "Enter month as mm:"
            Me.lbl2.Text = "Enter year as yyyy:"
            Me.btnDisplayList.Enabled = False
        ElseIf Me.optMonth.Checked Then
            Me.lbl1.Text = "Enter month as mm:"
            Me.btnDisplayList.Enabled = False
        ElseIf Me.optYear.Checked Then
            Me.lbl1.Text = "Enter year as yyyy:"
        ElseIf Me.optDTRange.Checked Then
            Me.lbl1.Text = "Enter first date and time as " & MyDateFormat().ToLower & " (inclusive):"
            Me.lbl2.Text = "Enter second date and time as " & MyDateFormat().ToLower & " (inclusive):"
        End If
        If Me.optDTRange.Checked Or Me.optTime.Checked Or Me.optMonthYear.Checked Then
            Me.lbl2.Visible = True
            Me.txt2.Visible = True
        Else
            Me.lbl2.Visible = False
            Me.txt2.Visible = False
        End If
        Me.txt1.Text = ""
        Me.txt2.Text = ""
    End Sub

    Friend Function QueryString() As String
        Select Case AssistType
            Case frmQueryAssist.enumAssist.StationID, frmQueryAssist.enumAssist.PCode, frmQueryAssist.enumAssist.CCode, frmQueryAssist.enumAssist.RCode, enumAssist.QCode, enumAssist.Agency, enumAssist.Validate
                If lstSelected.Items.Count = 1 Then
                    Return String.Format("= '{0}'", lstSelected.Items(0))
                Else
                    Dim StaList As String = ""
                    For Each s As String In lstSelected.Items
                        StaList &= IIf(StaList = "", "IN (", ", ")
                        StaList &= String.Format("'{0}'", s)
                    Next
                    StaList &= ")"
                    Return StaList
                End If
            Case frmQueryAssist.enumAssist.DateTimeValue
                If Me.optDateTime.Checked Then
                    Return String.Format("= {0}", Project.DB.DateTime(CDate(Me.txt1.Text)))
                ElseIf Me.optDate.Checked Then
                    Return String.Format("BETWEEN {0} and {1}", Project.DB.DateTime(CDate(Me.txt1.Text)), Project.DB.DateTime(CDate(Me.txt1.Text).AddDays(1).AddMinutes(-1)))
                ElseIf Me.optTime.Checked Then
                    Select Case Project.DB.DatabaseType
                        Case clsDB.enumDBType.Access, clsDB.enumDBType.Paradox, clsDB.enumDBType.DBase, clsDB.enumDBType.Excel, clsDB.enumDBType.Text, clsDB.enumDBType.SQL_Server, clsDB.enumDBType.SQL_Server_CE
                            Return String.Format("HOUR({2})={0} AND MINUTE({2})={1}", Me.txt1.Text, Me.txt2.Text, FieldName)
                        Case clsDB.enumDBType.SQLite
                            Return String.Format("STRFTIME('%H',{2})='{0}' AND STRFTIME('%M',{2})='{1}'", Me.txt1.Text, Me.txt2.Text, FieldName)
                        Case clsDB.enumDBType.Oracle
                            Return String.Format("TO_NUMBER(TO_CHAR({2},'HH24'))={0} AND TO_NUMBER(TO_CHAR({2},'MI'))={1}", Me.txt1.Text, Me.txt2.Text, FieldName)
                        Case Else
                            Return String.Format("EXTRACT(HOUR from {2})={0} AND EXTRACT(MINUTE from {2})={1}", Me.txt1.Text, Me.txt2.Text, FieldName)
                    End Select
                ElseIf Me.optMonthYear.Checked Then
                    Select Case Project.DB.DatabaseType
                        Case clsDB.enumDBType.Access, clsDB.enumDBType.Paradox, clsDB.enumDBType.DBase, clsDB.enumDBType.Excel, clsDB.enumDBType.Text, clsDB.enumDBType.SQL_Server, clsDB.enumDBType.SQL_Server_CE
                            Return String.Format("MONTH({2})={0} AND YEAR({2})={1}", Me.txt1.Text, Me.txt2.Text, FieldName)
                        Case clsDB.enumDBType.SQLite
                            Return String.Format("STRFTIME('%m',{2})='{0}' AND STRFTIME('%Y',{2})='{1}'", Me.txt1.Text, Me.txt2.Text, FieldName)
                        Case Else
                            Return String.Format("EXTRACT(MONTH from {2})={0} AND EXTRACT(YEAR from {2})={1}", Me.txt1.Text, Me.txt2.Text, FieldName)
                    End Select
                ElseIf Me.optMonth.Checked Then
                    Select Case Project.DB.DatabaseType
                        Case clsDB.enumDBType.Access, clsDB.enumDBType.Paradox, clsDB.enumDBType.DBase, clsDB.enumDBType.Excel, clsDB.enumDBType.Text, clsDB.enumDBType.SQL_Server, clsDB.enumDBType.SQL_Server_CE
                            Return String.Format("MONTH({1})={0}", Me.txt1.Text, FieldName)
                        Case clsDB.enumDBType.SQLite
                            Return String.Format("STRFTIME('%m',{1})='{0}'", Me.txt1.Text, FieldName)
                        Case Else
                            Return String.Format("EXTRACT(MONTH from {1})={0}", Me.txt1.Text, FieldName)
                    End Select
                ElseIf Me.optYear.Checked Then
                    Select Case Project.DB.DatabaseType
                        Case clsDB.enumDBType.Access, clsDB.enumDBType.Paradox, clsDB.enumDBType.DBase, clsDB.enumDBType.Excel, clsDB.enumDBType.Text, clsDB.enumDBType.SQL_Server, clsDB.enumDBType.SQL_Server_CE
                            Return String.Format("YEAR({1})={0}", Me.txt1.Text, FieldName)
                        Case clsDB.enumDBType.SQLite
                            Return String.Format("STRFTIME('%Y',{1})='{0}'", Me.txt1.Text, FieldName)
                        Case Else
                            Return String.Format("EXTRACT(YEAR from {1})={0}", Me.txt1.Text, FieldName)
                    End Select
                ElseIf Me.optDTRange.Checked Then
                    Return String.Format("BETWEEN {0} and {1}", Project.DB.DateTime(CDate(Me.txt1.Text)), Project.DB.DateTime(CDate(Me.txt2.Text).AddDays(1).AddMinutes(-1)))
                Else
                    Return ""
                End If
            Case enumAssist.RealValue
                If Me.optEqual.Checked Then
                    Return String.Format("= {0}", Me.txt1.Text)
                ElseIf Me.optLess.Checked Then
                    Return String.Format("< {0}", Me.txt1.Text)
                ElseIf Me.optGreater.Checked Then
                    Return String.Format("> {0}", Me.txt1.Text)
                ElseIf Me.optRange.Checked Then
                    Return String.Format("BETWEEN {0} and {1}", Me.txt1.Text, Me.txt2.Text)
                ElseIf Me.optWildcard.Checked Then
                    Return String.Format("LIKE {0}", Me.txt1.Text)
                ElseIf Me.optList.Checked Then
                    Dim ar() As String = Me.txt1.Text.Split(",")
                    Dim List As String = ""
                    For Each s As String In ar
                        If List <> "" Then List &= ", "
                        List &= String.Format("{0}", s)
                    Next
                    Return String.Format("IN ({0})", List)
                Else
                    Return ""
                End If
            Case enumAssist.StringValue
                If Me.optEqual.Checked Then
                    Return String.Format("= '{0}'", Me.txt1.Text)
                ElseIf Me.optLess.Checked Then
                    Return String.Format("< '{0}'", Me.txt1.Text)
                ElseIf Me.optGreater.Checked Then
                    Return String.Format("> '{0}'", Me.txt1.Text)
                ElseIf Me.optRange.Checked Then
                    Return String.Format("BETWEEN '{0}' and '{1}'", Me.txt1.Text, Me.txt2.Text)
                ElseIf Me.optWildcard.Checked Then
                    Return String.Format("LIKE '{0}'", Me.txt1.Text)
                ElseIf Me.optList.Checked Then
                    Dim ar() As String = Me.txt1.Text.Split(",")
                    Dim List As String = ""
                    For Each s As String In ar
                        If List <> "" Then List &= ", "
                        List &= String.Format("'{0}'", s)
                    Next
                    Return String.Format("IN ({0})", List)
                Else
                    Return ""
                End If
            Case Else
                Return ""
        End Select
    End Function

    Private Sub btnDisplayList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayList.Click
        Try
            With New frmList
                MainForm.WriteProgress("Retrieving unique values for " & FieldName & "...", ProgressBarStyle.Marquee)
                Dim Field As String = FieldName
                If Me.AssistType = enumAssist.DateTimeValue Then
                    If Me.optDate.Checked Or Me.optDTRange.Checked Then
                        Select Case Project.DB.DatabaseType
                            Case clsDB.enumDBType.SQLite
                                Field = String.Format("DATE({0})", FieldName)
                            Case Else
                                Field = String.Format("CAST({0} AS DATE)", FieldName)
                        End Select
                    ElseIf Me.optYear.Checked Then
                        Select Case Project.DB.DatabaseType
                            Case clsDB.enumDBType.Access, clsDB.enumDBType.SQL_Server, clsDB.enumDBType.SQL_Server_CE
                                Field = String.Format("YEAR({0})", FieldName)
                            Case clsDB.enumDBType.SQLite
                                Field = String.Format("STRFTIME('%Y',{0})", FieldName)
                            Case Else
                                Field = String.Format("EXTRACT(YEAR from {0})", FieldName)
                        End Select
                    End If
                End If
                For Each s As String In Project.DB.GetRecordList(TableName, Field)
                    If Me.FieldName.ToUpper = "DATE_TIME" Or Me.FieldName.ToUpper = "CREATE_UPDATE" Then
                        If Me.optDate.Checked Or Me.optDTRange.Checked And IsDate(s) Then
                            s = CDate(s).ToString(MyDateFormat)
                        ElseIf Me.optYear.Checked Then
                            s = s
                        Else
                            s = CDate(s).ToString(MyDateTimeFormat)
                        End If
                    End If
                    .ListBox1.Items.Add(s)
                Next
                MainForm.ProgressComplete()
                If Me.optList.Checked Then .ListBox1.SelectionMode = SelectionMode.MultiExtended Else .ListBox1.SelectionMode = SelectionMode.One
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    If LastTxt Is Nothing Then LastTxt = txt1
                    If Me.optList.Checked Then
                        For Each s As String In .ListBox1.SelectedItems
                            LastTxt.Text &= IIf(Me.txt1.Text = "", "", ", ") & s
                        Next
                    Else
                        LastTxt.Text = .ListBox1.SelectedItem
                    End If
                End If
            End With
            If LastTxt IsNot Nothing Then LastTxt.Focus()
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            MainForm.ProgressComplete()
        End Try
    End Sub

    Private Sub txt1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt1.TextChanged, txt2.TextChanged
        btnOK2.Enabled = False
        Dim s As String = CType(sender, TextBox).Text
        If s = "" Then Exit Sub
        If AssistType = enumAssist.RealValue Then
            If Not IsNumeric(s) Then Exit Sub
        ElseIf AssistType = enumAssist.DateTimeValue Then
            If optDateTime.Checked Or optDate.Checked Or optDTRange.Checked Then
                If Not IsDate(s) Then Exit Sub
            Else
                If Not IsNumeric(s) Then Exit Sub
            End If
        End If
        btnOK2.Enabled = True
    End Sub

    Private Sub txt_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txt1.Validating, txt2.Validating
        Dim s As String = CType(sender, TextBox).Text
        If Me.AssistType = enumAssist.RealValue Then
            If Not IsNumeric(s) Then WarningMsg("You must enter numeric values.") : e.Cancel = True : Exit Sub
        ElseIf Me.AssistType = enumAssist.DateTimeValue Then
            If Me.optDateTime.Checked Or Me.optDate.Checked Or Me.optDTRange.Checked Then
                If Not IsDate(s) Then WarningMsg("You must enter a valid date.") : e.Cancel = True : Exit Sub
            Else
                If Not IsNumeric(s) Then WarningMsg("You must enter numeric values.") : e.Cancel = True : Exit Sub
            End If
        End If
    End Sub

    Private Sub dgSupport_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles dgSupport.KeyPress
        If e.KeyChar = Chr(13) Then
            e.KeyChar = ""
            btnAdd.PerformClick()
        End If
    End Sub

    Private Sub btnSelectFromGroups_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectFromGroups.Click
        Try
            Dim GroupTable As String = "", GroupField As String = "", IDField As String = ""

            Select Case AssistType
                Case enumAssist.StationID
                    GroupTable = "StaGrp"
                    GroupField = "StationGroup"
                    IDField = "Station_ID"
                Case enumAssist.PCode
                    GroupTable = "PCodeGrp"
                    GroupField = "PCodeGroup"
                    IDField = "PCode"
            End Select
            With New frmSelect(False)
                .lstItems.Sorted = True
                .lstItems.Items.AddRange(Project.DB.GetRecordList(GroupTable, GroupField).ToArray)
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    Dim dr As DbDataReader = Project.DB.ExecuteReader("SELECT {0} FROM {1} WHERE {2}='{3}'", IDField, GroupTable, GroupField, .lstItems.Text)
                    While dr IsNot Nothing AndAlso dr.Read
                        Dim ID As String = TestNull(dr.GetValue(0), "")
                        If ID <> "" AndAlso Not lstSelected.Items.Contains(ID) Then lstSelected.Items.Add(ID)
                    End While
                    dr.Close()
                    UpdateSelected()
                End If
            End With
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub btnGIS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGIS.Click
        Try
            Dim lst As New Generic.List(Of String)
            If IsMWForm Then
                lst = CType(MainForm, frmMainMW).SelectedStations
            Else
                MainForm.CheckGisData()
                With New WRDB.Graph.frmGIS(Project, ActiveTableName, clsProject.TempData, Graph.frmGIS.enumMode.Select, MainWRDB.WRDBStationTypes)
                    If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                        lst = .SelectedStations
                    End If
                    .Dispose()
                End With
            End If
            lstSelected.Items.AddRange(lst.ToArray)
            UpdateSelected()
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub UpdateSelected()
        lblSelected.Text = lstSelected.Items.Count & " Items Selected"
        btnOK.Enabled = lstSelected.Items.Count > 0
    End Sub

End Class
